/*
 * Copyright (c) 2013 WDCY Information Technology Co. Ltd
 * www.wdcy.cc
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * WDCY Information Technology Co. Ltd ("Confidential Information").
 * You shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement you
 * entered into with WDCY Information Technology Co. Ltd.
 */
package mblog.web.interceptor;

import mblog.base.utils.URLUtils;
import mblog.base.utils.WebUtils;
import mblog.core.data.AccessLog;
import mblog.core.persist.service.AccessLogService;
import mblog.web.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author Wu Tianqiang
 */
public class AccessLogInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private AccessLogService accessLogService;

    private static String sysHost = "xianshiyue.com";
    private static String sysIP = "121.41.59.127";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String referer = request.getHeader("referer");
        String refererHost = URLUtils.getHost(referer);

        if (refererHost != null && (refererHost.contains(sysHost) || refererHost.contains(sysIP))) {
            return true;
        }

        String requestURL = request.getRequestURL().toString();
        String host = WebUtils.getIpAddr(request);
        String params = WebUtils.getParams(request);
        String headers = WebUtils.getHeaders(request);
        AccessLog accessLog = new AccessLog(requestURL, host, params, headers, new Date(), referer);
        accessLogService.add(accessLog);

        return true;
    }
}